package com.ruipeng.shengyapo.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ruipeng.shengyapo.comm.ResponseData;
import com.ruipeng.shengyapo.pay.alipay.config.AlipayConfig;
import com.ruipeng.shengyapo.pay.alipay.util.AlipayNotify;
import com.ruipeng.shengyapo.service.OrderService;
import com.ruipeng.shengyapo.service.UserService;
import com.ruipeng.shengyapo.utils.ContentUtils;
import com.ruipeng.shengyapo.utils.HttpUtils;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.HttpPost;
import org.apache.poi.util.SystemOutLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by tu_pei on 17/6/9.
 */
@Controller
public class AliPayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;
    /**
     * 支付宝回调商户地址
     */
    @SuppressWarnings({ "rawtypes", "unused" })
    @ResponseBody
    @RequestMapping(value="return_url")
    public void return_url(HttpServletRequest request, HttpSession session) {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//			try {
//				valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			}
            params.put(name, valueStr);
        }
        System.out.println("params = ");
        System.out.println("params = " + JSONObject.fromObject(params));
        System.out.println("params = ");
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        JSONObject orderInfo = JSONObject.fromObject(params);
        String out_trade_no = orderInfo.get("out_trade_no").toString();
        //支付宝交易号
        String trade_no = orderInfo.get("trade_no").toString();

        //交易状态
        String trade_status = params.get("trade_status").toString();
        String buyer_email = params.get("seller_email").toString();
        String total_fee = params.get("total_amount").toString();
        System.out.println("total_amount = " + total_fee);

        String notify_time = params.get("gmt_create");

        //计算得出通知验证结果
        if (trade_status.equals("TRADE_SUCCESS")) {//验证成功
            Map<String,Object> paramss = new HashMap<String,Object>();
            paramss.put("orderNo",out_trade_no);
            //判断订单是否存在
            Map<String, Object> orderMap = orderService.getOrderByOrderNo(paramss);
            if (orderMap == null) {
                System.out.println("  == = 判断订单是否存在===");
                orderService.updateOrderByOrderNo(out_trade_no,params.toString(),0,trade_no,out_trade_no);
            }

            String orderAmount = orderMap.get("tradeAmount").toString();
            String tradeStatus = orderMap.get("tradeStatus").toString();
            //判断金额和状态是否是未完成
            System.out.println("orderAmount="+orderAmount+",total_fee="+total_fee);
            if( !(Double.parseDouble(orderAmount)==Double.parseDouble(total_fee)) ){
                //用户已完成订单
                //回调金额和订单金额不相符
                System.out.println("  == = 回调金额和订单金额不相符===");
                orderService.updateOrderByOrderNo(out_trade_no,params.toString(),0,trade_no,out_trade_no);
            }else{

                if(!tradeStatus.equals("1")){
                    System.out.println("  == = 更新订单状态===");
                    //更新订单状态
                    int uOrderCount = orderService.updateOrderByOrderNo(out_trade_no,params.toString(),1,trade_no,out_trade_no);
                    System.out.println("  =uOrderCount="+uOrderCount);
                    Map<String,Object> updateUser = new HashMap<String,Object>();
                    updateUser.put("userId",orderMap.get("userId"));

                    System.out.println("tradeType="+orderMap.get("tradeType"));
                    Integer tradeType = Integer.parseInt(orderMap.get("tradeType").toString());

                    if(tradeType == 1){
                        //充值
                        updateUser.put("userAccount",total_fee);
                    }
                    if(tradeType == 2){
                        //交押金
                        updateUser.put("deposit",total_fee);
                    }
                    if(tradeType == 3){
                        //退押金
                        updateUser.put("deposit",0);
                    }
                    if( uOrderCount > 0 ){
                        //更新用户余额或者押金
                        System.out.println("  =updateUser="+JSONObject.fromObject(updateUser));
                        userService.updateUserInfo(updateUser);
                    }
                }
            }
        }else{
            //TRADE_ERROR 支付失败
            orderService.updateOrderByOrderNo(out_trade_no,params.toString(),0,trade_no,out_trade_no);
        }
    }
}
